
angular.module('U9ImHd.controllers')

.controller('LoginCtrl', ['$scope', 'AppManager', 'Device', 'DevicePort', 'imanDialog', 'User', 'Help', 
    function ($scope, AppManager, Device, DevicePort, imanDialog, User, Help) {
        $scope.data = {
            activeIndex: 1,
            usercode: '',
            password: '',
            autologin: Device.isTV()
        };

        $scope.clickTab = function (index) {
            $scope.data.activeIndex = index;
        };
        $scope.signin = function () {
            imanDialog.showLoading();
            User.signin(
                $scope.data.usercode, 
                $scope.data.password, 
                $scope.data.autologin
            ).then(function () {
                Help.goAsRoot('home');
            }).finally(function () {
                imanDialog.hideLoading();
            });
        };

        $scope.$on('$ionicView.beforeEnter', function () {
            DevicePort.open({
                device: 0,
                baudrate: 115200,
                parseFn: true
            });
        });
        $scope.$on('$ionicView.afterLeave', function () {
            DevicePort.close();
        });
        $scope.$on('$destroy', function () {
            DevicePort.close();
        });
        $scope.$on('devicePort.DataReceived', function (e, barcode) {
            if ($scope.data.activeIndex !== 2) {
                return;
            }
            imanDialog.showLoading();
            User.signinScan(barcode).then(function () {
                Help.goAsRoot('home');
            }).finally(function () {
                imanDialog.hideLoading();
            });
        });
    }
]);